package com.example.sunmiv1.vm

import com.example.sunmiv1.activity.good.GoodsManageActivity
import com.example.sunmiv1.adapter.GoodsManageAdapter
import com.example.sunmiv1.entity.NewGoodsListBean
import com.example.sunmiv1.room.BaseApp
import com.example.sunmiv1.room.MerchandiseDaoManager
import com.example.sunmiv1.room.entity.MerchandisePrintEntity
import com.example.sunmiv1.utils.net.ACache
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.CopyOnWriteArrayList

public class GoodsMangerViewModel(private val mActivity:GoodsManageActivity){
    private val mACache by lazy {
        ACache.get(mActivity)
    }
    private val mList=CopyOnWriteArrayList<MerchandisePrintEntity>()
    fun init(){
        GlobalScope.launch(Dispatchers.IO){
            val list=MerchandiseDaoManager.getAll()
            mList.clear()
            mList.addAll(list)
        }
    }
    fun addPrint(entity: MerchandisePrintEntity){
        GlobalScope.launch(Dispatchers.IO){
            MerchandiseDaoManager.add(entity)
        }
    }
    fun addPrint(item: NewGoodsListBean.DataBean,adapter: GoodsManageAdapter){
        GlobalScope.launch(Dispatchers.IO){
            val list=MerchandiseDaoManager.findMerchandiseId(item.id)
            val merchantid=ACache.get(BaseApp.getInstall()).getAsString("merchantid")?:""
            if(list.isEmpty()){
                MerchandiseDaoManager.add(MerchandisePrintEntity(merchantid,item.id,item.goods_name?:"",false))
            }else{
                list.first().also {
                    it.isPrint=!it.isPrint
                    it.merchandiseName=item.goods_name
                    MerchandiseDaoManager.add(it)
                }
            }
            mList.clear()
            mList.addAll(MerchandiseDaoManager.getAll())
            GlobalScope.launch(Dispatchers.Main){
                adapter.notifyDataSetChanged()
            }
        }
    }
    fun find(item: NewGoodsListBean.DataBean):MerchandisePrintEntity?{
        val merchantid=ACache.get(BaseApp.getInstall()).getAsString("merchantid")?:""
        val first=mList.firstOrNull {
            it.userId==merchantid && it.merchandiseId==item.id
        }
        return first
    }
    fun getList()=mList
}